//
//  GFCityListViewController.m
//  GoodFood
//
//  Created by dllo on 15/11/4.
//  Copyright © 2015年 荣伟峰. All rights reserved.
//

#import "GFCityListViewController.h"

@interface GFCityListViewController ()<UITableViewDataSource, UITableViewDelegate, BMKLocationServiceDelegate, BMKGeoCodeSearchDelegate>

@property (nonatomic, strong) BMKGeoCodeSearch *geoCodeSearch;
@property (nonatomic, strong) NSMutableArray *cityArr;
@property (nonatomic, strong) UITableView *cityTableView;
@property (nonatomic, strong) NSMutableArray *titleArr;
@property (nonatomic, strong) NSMutableArray *tempArr;
@property (nonatomic, strong) BMKLocationService *locService;
@property (nonatomic, assign) double lat;
@property (nonatomic, assign) double lon;
@property (nonatomic, copy) NSString *cityName;//根据定位坐标得到的城市名

@end

@implementation GFCityListViewController

-(void)viewWillAppear:(BOOL)animated {
    
    [super viewWillAppear:animated];
    [self locServiceData];
    self.locService.delegate = self;
    self.geoCodeSearch = [[BMKGeoCodeSearch alloc] init];
    self.geoCodeSearch.delegate = self;
}

-(void)viewWillDisappear:(BOOL)animated {
    
    [super viewWillDisappear:animated];
    self.locService.delegate = nil;
    self.geoCodeSearch.delegate = nil;
    
}

//定位
-(void)locServiceData {
    
    self.locService = [[BMKLocationService alloc] init];
    [self.locService startUserLocationService];
}

-(void)handleData {
    
    
    
    NSString *str = @"http://api.meishixing.com/other/config/getcitylist";
    [AFNetHandle GETWithURL:str body:nil httpHead:nil responseStyle:JSON success:^(id result) {
       
        self.cityArr = [NSMutableArray array];
        self.titleArr = [NSMutableArray array];
        
        NSArray *tempArr = [result objectForKey:@"result"];
        for (NSDictionary *dic in tempArr) {
            GFCityListModel *model = [GFCityListModel modWithDic:dic];
            NSArray *cityNameArr = model.city_list;
            if (![model.begin_key isEqualToString:@"hot"]) {
                for (NSDictionary *dicc in cityNameArr) {
                    if ([self.cityName containsString:dicc[@"city_name"]]) {
                        NSMutableArray *arr = [NSMutableArray array];
                        [arr addObject:dicc];
                        NSDictionary *tempDic = @{@"city_list":arr, @"begin_key":@"⚑"};
                        GFCityListModel *model = [GFCityListModel modWithDic:tempDic];
                        [self.cityArr insertObject:model atIndex:0];
                        [self.titleArr insertObject:model.begin_key atIndex:0];
                    }
                }
            }
            [self.cityArr addObject:model];
            if ([model.begin_key isEqualToString:@"hot"]) {
                model.begin_key = @"☀︎";
            }
            [self.titleArr addObject:model.begin_key];
        }
        [self.cityTableView reloadData];
    } fail:^(NSError *error) {
        
    }];
    
    
}

-(void)creatCityTableView {
    
    self.cityTableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 64, ScreenWidth, ScreenHeight - 64) style:UITableViewStylePlain];
    //更改索引颜色
    self.cityTableView.sectionIndexBackgroundColor = [UIColor clearColor];
    self.cityTableView.sectionIndexColor = [UIColor colorWithWhite:0.348 alpha:1.000];
    self.cityTableView.delegate = self;
    self.cityTableView.dataSource = self;
    [self.view addSubview:self.cityTableView];
    
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.automaticallyAdjustsScrollViewInsets = NO;
    [self creatCityTableView];
    
    UIBarButtonItem *backItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"houtui1"] style:UIBarButtonItemStylePlain target:self action:@selector(backToLastVC:)];
    self.navigationItem.leftBarButtonItem = backItem;
    
    
}

- (void)backToLastVC:(UIBarButtonItem *)item {
    
    [self.navigationController popViewControllerAnimated:YES];
    
    YRSideViewController *con = (YRSideViewController *)[UIApplication sharedApplication].keyWindow.rootViewController;
    
    [con showLeftViewController:YES];
}


-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    
    return self.cityArr.count;
    
}

-(NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
    GFCityListModel *model = [self.cityArr objectAtIndex:section];
    
    if ([model.begin_key isEqualToString:@"☀︎"]) {
        model.begin_key = @"热门城市";
    }
    
    if ([model.begin_key isEqualToString:@"⚑"]) {
        model.begin_key = @"当前所在城市";
    }
    return model.begin_key;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    
    GFCityListModel *model = [self.cityArr objectAtIndex:section];
    
    return model.city_list.count;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    GFCityListModel *model = [self.cityArr objectAtIndex:indexPath.section];
    
    static NSString *str = @"city";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:str];
    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:str];
    }
    NSDictionary *dic = [model.city_list objectAtIndex:indexPath.row];
    cell.textLabel.text = [dic objectForKey:@"city_name"];
    
    return cell;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    
    GFCityListModel *model = [self.cityArr objectAtIndex:indexPath.section];
    NSDictionary *dic = [model.city_list objectAtIndex:indexPath.row];
    GFNearHomeViewController *nearHomeVC = [[GFNearHomeViewController alloc] init];
    nearHomeVC.city_id = [dic objectForKey:@"city_id"];
    nearHomeVC.cityID = 1;
    [self.navigationController pushViewController:nearHomeVC animated:YES];
    
}

-(NSArray<NSString *> *)sectionIndexTitlesForTableView:(UITableView *)tableView {

    return self.titleArr;
}

-(void)didUpdateBMKUserLocation:(BMKUserLocation *)userLocation {
    
    self.lat = userLocation.location.coordinate.latitude;
    self.lon = userLocation.location.coordinate.longitude;
    if (self.lat != 0 && self.lon != 0) {
        [self.locService stopUserLocationService];
    }
    
}

#pragma mark - 返向地理编码

-(void)cityForName {
    
   
    CLLocationCoordinate2D pt = (CLLocationCoordinate2D){0, 0};
    pt = CLLocationCoordinate2DMake(self.lat, self.lon);
    BMKReverseGeoCodeOption *reverseGeocodeSearchOption = [[BMKReverseGeoCodeOption alloc]init];
    reverseGeocodeSearchOption.reverseGeoPoint = pt;
    [self.geoCodeSearch reverseGeoCode:reverseGeocodeSearchOption];

}

-(void)didStopLocatingUser {
    
    [self cityForName];
    
}

-(void)onGetReverseGeoCodeResult:(BMKGeoCodeSearch *)searcher result:(BMKReverseGeoCodeResult *)result errorCode:(BMKSearchErrorCode)error {
    
    if (error == 0) {
        self.cityName = result.addressDetail.city;
        [self handleData];
        
    } else {
        
        NSLog(@"%d", error);
    }
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
